package com.rainng.coursesystem.scheduledjob;


import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import com.rainng.coursesystem.model.entity.VisBatchEntity;
import com.rainng.coursesystem.module.task.service.BatchService;
import com.rainng.coursesystem.service.DeviceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Component
@EnableScheduling   // 1.开启定时任务
@EnableAsync        // 2.开启多线程
@Slf4j
public class JobTasks {

    @Resource
    private BatchService batchService;

    @Resource
    private DeviceService deviceService;

//    @Scheduled(cron = "0 0 2 * * ?")
    @Scheduled(cron = "0 32 11 * * ?")
    public void refreshDeviceStatus(){
        deviceService.refreshStatus();
    }


    //定时任务新增批次
    // 需求尚未明确，现在是新增一个月，按甲方需求是不论什么时候开始，都是次月25号结束，然后要跳过非法定节假日
    //@Scheduled(cron = "0 39,40 11 * * ?")
    //@Scheduled(cron = "0 0 1 * * ?")
    public void addBatchTask() {

        log.info("判断批次");
        List<VisBatchEntity> ves = batchService.getThisBatchInfo();
        if(ves == null){
            log.error("没有当前批次");
            log.warn("注意及时修改名称");
            return;
        }
        if(ves.size() > 0) {
            VisBatchEntity newbatch = ves.get(ves.size()-1);
            Date endtime = newbatch.getEndTime();
            String lastbatchendday = DateUtil.format(endtime, "yyyy-MM-dd");

            VisBatchEntity v = new VisBatchEntity();
            String today = DateUtil.format(new Date(), "yyyy-MM-dd");
            if(today.equals(lastbatchendday)){

                String name = ves.get(ves.size()-1).getName();
                Date nbstarttime = DateUtil.parse(today, "yyyy-MM-dd");
                Date nbendtime = DateUtil.offset(nbstarttime, DateField.MONTH, 1);
                nbendtime = DateUtil.offset(nbendtime, DateField.HOUR, 23);
                nbendtime = DateUtil.offset(nbendtime, DateField.MINUTE, 59);
                nbendtime = DateUtil.offset(nbendtime, DateField.SECOND, 59);
                try{
                    Integer nbname = Integer.valueOf(name) + 1;
                    v.setName(nbname.toString());
                }catch (Exception e){
                    v.setName("新批次"+today);
                }
                v.setCreateTime(new Date());
                v.setStartTime(nbstarttime);
                v.setEndTime(nbendtime);
                boolean i = batchService.save(v);
                log.info("新增批次成功");
                return;
            }

            log.info("本日无需新增批次");
        }


        }







}
